<?php

namespace App\Service\Renew;

use App\Enums\Workflow\WorkflowEnum;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Fee\FeeAnnualOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Models\Workflow\WorkflowOrderNodeModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\BaseService;
use Illuminate\Support\Facades\Cache;

class RenewService extends BaseService
{
    private int $shopId;

    public function __construct(int $shopId)
    {
        $this->shopId = $shopId;
    }

    public static function getSingleton(int $shopId): self
    {
        return Cache::store('array')->remember("RenewService:{$shopId}", 120, function () use ($shopId) {
            return new self($shopId);
        });
    }

    /**
     * 续签条件
     * @return array
     */
    public function condition(): array
    {
        // 待缴费年费订单
        $fee   = FeeAnnualOrderModel::query()
                                    ->where('shopId', $this->shopId)
                                    ->where('payStatus', '!=', FeeAnnualOrderModel::PAY_STATUS_OK)
                                    ->count();
        $feeOrderNo = FeeAnnualOrderModel::query()
                                    ->where('shopId', $this->shopId)
                                    ->where('payStatus', '!=', FeeAnnualOrderModel::PAY_STATUS_OK)->value('feeOrderNo');

        // 违约函
        $againstNum   = CruiseCheckAgainstModel::query()
                                            ->where('shopId', $this->shopId)
                                            ->where('status', CruiseCheckAgainstModel::STATUS_WAIT)
                                            ->count();
        $against = CruiseCheckAgainstModel::query()
                                            ->where('shopId', $this->shopId)
                                            ->where('status', CruiseCheckAgainstModel::STATUS_WAIT)
                                            ->first();
        $againstUrl = '';
        if ($against) {
            $againstId  = $against->id;
            if ($against->level == CruiseCheckAgainstModel::LEVEL_PUNISH) {
                $againstUrl = config('open-shop.m') . "audit/pay-fine?againstId={$againstId}&shopId={$this->shopId}";
            } else {
                $againstUrl = config('webUrl.notify_web_cdn_url') . '#/pages/audit/report/break-contract?againstId=' . $againstId;
            }
        }

        // 整改单
        $rectify = CruiseCheckRectifyModel::query()
                                          ->where('shopId', $this->shopId)
                                          ->whereIn('status', [CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT, CruiseCheckRectifyModel::STATUS_WAIT_AUDIT])
                                          ->count();

        // rms
        $rms = RmsShopRemote::getShopDetailByShopId($this->shopId);

        // 夸父收银
        $kfPos = $rms['fyOpenStatus'] ?? false;

        // 夸父监控
        $kfMonitor = $rms['cameraOpenStatus'] ?? false;

        // 夸父商屏
        $kfScreen = $rms['tvOpenStatus'] ?? false;

        return [
            'feeNum'     => $fee,
            'feeUrl'     => config('open-shop.m') . "order/sign/{$feeOrderNo}/annualFee/{$this->shopId}",
            'againstNum' => $againstNum,
            'againstUrl' => $againstUrl,
            'rectifyNum' => $rectify,
            'rectifyUrl' => config('webUrl.notify_web_cdn_url') . "#/pages/audit/rectify/list",
            'kfPos'      => $kfPos,
            'kfMonitor'  => $kfMonitor,
            'kfScreen'   => $kfScreen,
        ];
    }

    /**
     * 续签用户信息
     * @return array
     */
    public function userInfo(): array
    {
        $identifyInfo = [];

        $orderNos = OpenShopMainProcessModel::query()->where('shopId', $this->shopId)->pluck('orderNo');

        $contract = OpenShopUserContractModel::query()
                                             ->whereIn('orderNo', $orderNos)
                                             ->whereIn("contractType", OpenShopUserContractModel::OPEN_SHOP_CONTRACT_GROUP)
                                             ->where('detailStatus', 'COMPLETE')
                                             ->count();

        // 契约锁签过合同
        if ($contract) {
            $identifyInfoModel = OpenShopUserIdentityCardModel::query()
                                                              ->whereIn('orderNo', $orderNos)
                                                              ->orderByDesc('id')
                                                              ->first();
            if ($identifyInfoModel) {
                $mobile = OpenShopUserBaseInfoModel::query()
                                                   ->whereIn('orderNo', $orderNos)
                                                   ->orderByDesc('id')
                                                   ->where('mobile', '!=', '')
                                                   ->value('mobile');

                $identifyInfo = [
                    'name'             => $identifyInfoModel->name,
                    'phone'            => $mobile,
                    'idCard'           => $identifyInfoModel->identityCardNumber,
                    'frontSideImg'     => $identifyInfoModel->frontSideImg,
                    'backSideImg'      => $identifyInfoModel->backSideImg,
                    'effectiveEndDate' => date('Y-m-d', $identifyInfoModel->effectiveEndTime),
                    'effectiveStartDate' => date('Y-m-d', $identifyInfoModel->effectiveStartTime),
                ];
            }

            // 主单
            $mainProcess = OpenShopMainProcessModel::getMainOrder($this->shopId);
            if ($mainProcess) {
                $orderNo = $mainProcess->orderNo ?? '';

                $baseInfo = OpenShopUserBaseInfoModel::query()->where('orderNo', $orderNo)->first();
                if ($baseInfo) {

                    $addressPrefix = explode('-', $baseInfo['addressPrefix']);

                    // 省市区
                    $identifyInfo['addressPrefixArr'] = [
                        [
                            'text' => $addressPrefix[0] ?? '',
                            'value' => $baseInfo['provinceCode'],
                        ],
                        [
                            'text' => $addressPrefix[1] ?? '',
                            'value' => $baseInfo['cityCode'],
                        ],
                        [
                            'text' => $addressPrefix[2] ?? '',
                            'value' => $baseInfo['districtCode'],
                        ],
                    ];

                    // 详细地址
                    $identifyInfo['addressDetail'] = $baseInfo->address;

                    // email
                    $identifyInfo['email'] = $baseInfo->email;

                    // 微信
                    $identifyInfo['wechat'] = $baseInfo->weChatNumber;

                    // 银行卡号
                    $identifyInfo['cardNo'] = $baseInfo->cardNo;

                    // 开户行
                    $identifyInfo['cardBankName'] = $baseInfo->cardBankName;

                    // 银行卡账户名称
                    $identifyInfo['cardAccountName'] = $baseInfo->cardAccountName;
                }
            }
        }

        return $identifyInfo;
    }

    public static function getWorkflow(string $workflowNo): array
    {
        $workflowOrder = WorkflowOrderModel::query()
                                           ->where('workflowNo', $workflowNo)
                                           ->where('workflowType', WorkflowEnum::WORKFLOW_TYPE_OPEN_SHOP_RENEW)
                                           ->first();

        if (!$workflowOrder) {
            BaseService::throwErr('门店不存在续签工单');
        }

        // 申请单node
        $workflowNode = WorkflowOrderNodeModel::query()
                                              ->where('workflowOrderId', $workflowOrder->id)
                                              ->where('businessType', WorkflowEnum::BUSINESS_TYPE_SUBMIT_APPLY)
                                              ->first();
        if (!$workflowNode) {
            BaseService::throwErr('审批流中未找到申请单');
        }

        return [$workflowOrder, $workflowNode];
    }
}
